import React, { Component } from 'react'
import axios from 'axios'

export default class Login extends Component {
    state = {
        username:'',
        password:''
    }
    render() {
        let {username,password} = this.state;
        return (
            <div>
                <input type="text" placeholder="用户名" name="username" value={username} onChange={this.change}/>
                <input type="text" placeholder="密码" name="password" value={password}  onChange={this.change}/>
                <button onClick={this.login}>登录</button>
            </div>
        )
    }

    change = (e) => {
        this.setState({
            [e.target.name]:e.target.value
        })
    }

    //登录
    login = () => {
        let {username,password} = this.state;
        axios.post('/api/login',{username,password}).then(res => {
            if(res.data.code === 1){
                let {token,rolename} = res.data;
                localStorage.setItem('token',token);
                localStorage.setItem('userinfo',JSON.stringify({username,rolename}));
                this.props.history.push('/main')
            }else{
                alert(res.data.msg)
            }
        })
    }
}
